package com.zwb.demo.easyweb.common.entity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.util.Assert;

import java.util.stream.Stream;

public interface ValueEnum<V> {

    /**
     * Converts value to corresponding enum.
     *
     * @param enumType enum type
     * @param value database value
     * @param <V> value generic
     * @param <E> enum generic
     * @return corresponding enum
     */
    @JsonCreator
    static <V, E extends ValueEnum<V>> E valueToEnum(Class<E> enumType, V value) {
        Assert.notNull(enumType, "enum type must not be null");
        Assert.notNull(value, "value must not be null");
        Assert.isTrue(enumType.isEnum(), "type must be an enum type");

        return Stream.of(enumType.getEnumConstants())
                .filter(item -> item.getValue().equals(value))
                .findFirst()
                .orElseThrow(
                        () -> new IllegalArgumentException("unknown database value: " + value));
    }

    /**
     * Gets enum key.
     *
     * @return enum key
     */
    String getKey();

    /**
     * Gets enum value.
     *
     * @return enum value
     */
    @JsonValue
    V getValue();
}
